import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RSATest {

    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();


    public static String toHex(byte[] value) {
        StringBuilder sb = new StringBuilder(value.length * 2);
        int len = value.length;
        for (int i = 0; i < len; i++) {
            int hi = (value[i] & 0xff) >>> 4;
            int lo = value[i] & 0x0f;
            sb.append(HEX_DIGITS[hi]).append(HEX_DIGITS[lo]);
        }
        return sb.toString();
    }

    public static void main(String[] args) throws IOException,
            NoSuchAlgorithmException,
            InvalidKeyException, SignatureException {

        byte[] publicKeyBytes = readFile("public_key.der");
        byte[] signedData = readFile("signed_data.bin");
        byte[] sigBytes = readFile("sig_1.bin");

        String keyAlgorithm = "RSA";

        PublicKey publicKey;
        try {
            publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(
                    new X509EncodedKeySpec(publicKeyBytes));
        } catch (Exception e) {
            System.out.println(e);
            return;
        }

        String jcaSignatureAlgorithm = "SHA256withRSA";
        try {
            Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
            sig.initVerify(publicKey);
            sig.update(signedData);

            if (sig.verify(sigBytes)) {
                System.out.println("验证成功。");
            } else {
                System.out.println("验证失败。");
            }

        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }

    private static byte[] readFile(String filename) throws IOException {
        File file = new File(filename);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        byte[] bytes = new byte[(int) file.length()];
        bis.read(bytes);
        bis.close();
        return bytes;
    }

}
